<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-select v-if="false" v-model="listQuery.lineNumber" :placeholder="$t('equipment.lineNumber')" class="filter-item" style="width: 200px" @change="handleLineSelect">
        <el-option v-for="item in lineOptions" :key="item.lineNumber" :label="item.lineName+ '_'+item.lineNumber" :value="item.lineNumber" />
      </el-select> -->
      <!-- <el-select v-model="listQuery.stationNumber" :placeholder="$t('equipment.stationNumber')" class="filter-item" clearable="" style="width: 250px" @change="handleFilter">
        <el-option v-for="item in stationOptions" :key="item.stationNumber" :label="item.stationName+ '_'+item.stationNumber" :value="item.stationNumber" />
      </el-select> -->
      <el-select v-model="listQuery.processNumber" :placeholder="$t('equipment.processNumber')" class="filter-item" clearable="" style="width: 350px" @change="handleFilter">
        <el-option v-for="process in processOptions" :key="process.processNumber" :label="process.processName+'_'+process.processNumber" :value="process.processNumber" />
      </el-select>
      <el-input v-model="listQuery.failReason" clearable :placeholder="$t('rework.abnormalReason')" style="width: 250px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('common.creatNew') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('common.export') }}
      </el-button>
      <!-- 从工厂服务器下载数据 -->
      <el-button
        v-if="editRight"
        v-waves
        class="filter-item"
        type="warning"
        icon="el-icon-download"
        @click="handleDownloadFail"
      >
        {{ $t('rework.handleDownloadFail') }}
      </el-button>
    </div>
    <!-- 主界面数据 -->
    <el-table
      ref="dragTable"
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :header-row-style="{color: 'black'}"
      :header-cell-style="{background: 'lightBlue'}"
      border
      fit
      row-key="id"
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column :label="$t('rework.failId')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.failId }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('rework.defectCode')" width="150px" align="center">
        <template slot-scope="{row}">
          <span class="link-type" @click="goFailDetail(row.defectCode)">{{ row.defectCode }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column :label="$t('equipment.lineNumber')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.lineNumber }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column :label="$t('equipment.stationNumber')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.stationNumber }}</span>
        </template>
      </el-table-column> -->
      <el-table-column :label="$t('rework.subRank')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.rank }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.processNumber')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.processNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('rework.abnormalReason')" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.failReason }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.operation')" align="center" width="200px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('common.edit') }}
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 新建和更新对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 600px; margin-left:50px;">
        <el-form-item :label="$t('equipment.processNumber')" required prop="processNumber">
          <el-select v-model="temp.processNumber" :placeholder="$t('equipment.processNumber')" class="filter-item" clearable="" style="width: 450px">
            <el-option v-for="process in processOptions" :key="process.processNumber" :label="process.processName+'_'+process.processNumber" :value="process.processNumber" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('rework.defectCode')" required prop="defectCode">
          <el-input v-model="temp.defectCode" :placeholder="$t('rework.defectCode')" />
        </el-form-item>
        <el-form-item :label="$t('equipment.stationNumber')" required prop="stationNumber">
          <el-input v-model="temp.stationNumber" :placeholder="$t('equipment.stationNumber')" />
        </el-form-item>
        <el-form-item :label="$t('equipment.lineNumber')" required prop="lineNumber">
          <el-input v-model="temp.lineNumber" :placeholder="$t('equipment.lineNumber')" />
        </el-form-item>
        <el-form-item :label="$t('rework.rank')" required prop="rank">
          <el-input v-model="temp.rank" :placeholder="$t('rework.rank')" />
        </el-form-item>
        <el-form-item :label="$t('rework.abnormalReason')" required prop="failReason">
          <el-input
            v-model="temp.failReason"
            clearable
            :placeholder="$t('msg.CHARACTER_LESS_THAN')+120"
            :autosize="{ minRows: 5, maxRows: 10}"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 点击下载弹窗 -->
    <el-dialog :title="$t('rework.downloadFail')" :visible.sync="dialogForm" class="diag">
      <el-table
        :key="tableKey"
        :data="processOptions"
        :header-row-style="{color: 'black'}"
        :header-cell-style="{background: 'lightBlue'}"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column :label="$t('equipment.processNumber')" width="auto" align="center">
          <template slot-scope="{row}">
            <span class="link-type" @click="downloadList(row.processNumber)">{{ row.processNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('equipment.processName')" width="auto" align="center">
          <template slot-scope="{row}">
            <span>{{ row.processName }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="editRight"
          v-waves
          class="filter-item"
          type="primary"
          icon="el-icon-download"
          @click="downloadList()"
        >
          {{ $t('rework.downloadAll') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getStationListEx, getProcessList } from '@/api/equipment'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getFailList, creatFail, updateFail, deleteFail, downloadFailList } from '@/api/rework'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import i18n from '@/lang'
// import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui

export default {
  name: 'FailDef',
  components: {
    Pagination
  },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      total: 0,
      editRight: true,
      tableKey: 0,
      list: [],
      // newList: [],
      // sortable: null,
      // lineOptions: [],
      // 选择下拉框
      stationOptions: [],
      // 任务u状态
      // stateOptions: [{ label: '所有', key: 0, color: 'white' },
      //   { label: '进行中', key: 1, color: 'green' },
      //   { label: '延期', key: 2, color: 'orange' },
      //   { label: '完成', key: 3, color: 'darkblue' },
      //   { label: '取消', key: 4, color: 'red' },
      //   { label: '暂停', key: 5, color: 'yellow' }],
      listLoading: false,
      orderListQuery: {
        lineNumber: '',
        processNumber: ''
      },
      listQuery: {
        page: 1,
        limit: 20,
        state: 0,
        lineId: this.$store.getters.lineId,
        lineName: '',
        lineNumber: this.$store.getters.lineNumber,
        processNumber: '',
        resultCode: '',
        failReason: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+processNumber'
      },
      // showReviewer: false,
      // showRemark: false,
      temp: {
        failId: 0,
        defectCode: '',
        lineNumber: '',
        processNumber: '',
        failReason: '',
        rank: 0,
        stationNumber: ''
      },
      processOptions: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      dialogPvVisible: false,
      dialogForm: false,
      // pvData: [],
      rules: {
        processNumber: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        stationNumber: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        lineNumber: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        rank: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        defectCode: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        failReason: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }]
      },
      downloadLoading: false
      // searchLoading: {
      //   director: false
      // },
      // searchDialogStatus: '',
      // searchDialogFormVisible: {
      //   director: false
      // }
    }
  },
  // watch: {
  //   $route: {
  //     handler(val) {
  //       if (this.$route.query.lineNumber !== undefined && this.$route.query.stationNumber !== undefined) {
  //         this.listQuery.lineNumber = this.$route.query.lineNumber
  //         this.listQuery.stationNumber = this.$route.query.stationNumber
  //         // this.getLineOptions()
  //         this.getStationOptions()
  //         this.getList()
  //       }
  //     }
  //   }
  // },
  created() {
    this.editRight = (this.$store.getters.roles === 'admin' || this.$store.getters.roles === 'administrator')
    this.listQuery.lineNumber = this.$store.getters.lineNumber
    this.getList()
    this.getProcessOptions()
  },
  methods: {
    // timestepToolTip(index) {
    //   return index + '%'
    // },
    // formatDateTime(date) {
    //   return date.substring(0, 10)
    // },
    // 点击下载唤出弹窗
    handleDownloadFail() {
      // console.log(this.listQuery.lineNumber)
      this.dialogForm = true
    },
    goFailDetail(data) {
      // console.log(data)
      this.$router.push({ name: 'FailDetail', params: { defectCode: data }})
    },
    // 下载不合格动作
    downloadList(data) {
      this.orderListQuery.lineNumber = this.listQuery.lineNumber
      if (data === undefined) {
        this.orderListQuery.processNumber = ''
      } else {
        this.orderListQuery.processNumber = data
      }
      this.$confirm(i18n.t('produce.downloadOrNot'), i18n.t('common.tip'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        downloadFailList(this.orderListQuery).then(response => {
          this.getList()
          this.$message({
            type: 'success',
            message: i18n.t('msg.DOWNLOAD_SUCCESS')
          })
          this.listLoading = false
        })
      })
    },
    // 获取工艺流程选项
    getStationOptions() {
      this.listLoading = true
      this.stationOptions = []
      getStationListEx(this.listQuery).then(response => {
        this.stationOptions = response.data.stations
        this.listLoading = false
      })
    },
    // 判断线体ID是否为空
    isEmptyLineId() {
      var ret = (this.listQuery.lineNumber === undefined || this.listQuery.lineNumber === '')
      if (ret) {
        this.$notify({
          title: this.$i18n.t('common.tip'),
          message: i18n.t('msg.NO_LINE_SELECTED'),
          type: 'success',
          duration: 2000
        })
      }
      return ret
    },
    // 获取清单
    getList() {
      if (this.isEmptyLineId() === false) {
        this.listLoading = true
        getFailList(this.listQuery).then(response => {
          this.list = response.data.fails
          this.total = response.data.total
          this.listLoading = false
        })
      }
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 初始化创建信息
    resetTemp() {
      this.temp = {
        failId: 0,
        defectCode: '',
        lineNumber: this.$store.getters.lineNumber,
        processNumber: '',
        failReason: '',
        rank: '',
        stationNumber: ''
      }
    },
    // 新建一个数据
    handleCreate() {
      if (this.isEmptyLineId() === false) {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      }
    },
    // 获取工艺流程选项
    getProcessOptions() {
      this.listLoading = true
      this.processOptions = []
      getProcessList(this.listQuery).then(response => {
        this.processOptions = response.data.processes
        this.listLoading = false
      })
    },
    // 创建数据
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.lineNumber = this.listQuery.lineNumber
          creatFail(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.CREAT_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    // 点击编辑按钮
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据到数据库
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.lineNumber = this.$store.getters.lineNumber
          updateFail(this.temp).then(response => {
            const index = this.list.findIndex(v => v.failId === this.temp.failId)
            this.list.splice(index, 1, response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.UPDATE_SUCCESS'),
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 删除数据库信息
    handleDelete(row, index) {
      this.$confirm(i18n.t('msg.DELET_INFO_CONFIRM'), i18n.t('common.warn'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      })
        .then(async() => {
          this.temp = Object.assign({}, row) // copy obj
          this.temp.lineNumber = this.$store.getters.lineNumber
          deleteFail(this.temp).then(() => {
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.DELET_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
            this.getList()
          })
        })
        .catch(err => { console.error(err) })
    },
    // 下载所有导出信息
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          i18n.t('rework.abnormalNumber'),
          i18n.t('equipment.lineNumber'),
          i18n.t('equipment.processNumber'),
          i18n.t('rework.abnormalReason')]
        const filterVal = ['abnormalNumber', 'lineNumber', 'processNumber', 'failReason']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '不合格定义' + parseTime(Date.now(), '{y}{m}{d}{h}{i}{s}')
        })
        this.downloadLoading = false
      })
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  height: 800px;
  background-color: white;
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px x0;
    //margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
